/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 *
 */
import path from 'path';

import { FileSet, TaskInputValue } from '@ohos/hvigor';
import * as fse from 'fs-extra';

import { BuildArtifactConst } from '../../const/build-directory-const.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { checkAppPreloadHintStartupTasksSrcEntry } from '../../utils/task-util.js';
import { ValidateUtil } from '../../utils/validate/validate-util.js';
import { BasePackHapTask } from '../base/base-pack-hap-task.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';

import Task = TaskNames.Task;

/**
 * Fast packaging hsp task
 *
 * @since 2025/2/27
 */
export class FastPackageHsp extends BasePackHapTask {
  constructor(taskService: TargetTaskService) {
    super(taskService, Task.FAST_PACKAGE_HSP, 'hsp', OhosLogger.getLogger(FastPackageHsp.name));
  }

  declareInputs(): Map<string, TaskInputValue> {
    const map = super.declareInputs();
    map.set('harLocalDependencyCheck', !!this.targetService.getBuildOption().strictMode?.harLocalDependencyCheck);
    return map;
  }

  declareInputFiles(): FileSet {
    const fileSet = super.declareInputFiles();
    if (fse.existsSync(this.intermediateTempStartupFilePath)) {
      fileSet.addEntry(this.intermediateTempStartupFilePath);
    }
    return fileSet;
  }

  async beforeAlwaysAction(): Promise<void> {
    await super.beforeAlwaysAction();
  }

  protected async doTaskAction() {
    // 检查启动框架配置文件中appPreloadHintStartupTasks srcEntry配置的so在libs下存在
    const baseNativeLibsPath = path.resolve(this.pathInfo.getIntermediatesPatch(), BuildArtifactConst.BASE_NATIVE_LIBS_JSON);
    checkAppPreloadHintStartupTasksSrcEntry(this.intermediateTempStartupFilePath, baseNativeLibsPath, this._log, this.moduleName);

    const allDependency = this.service.getAllDependencies();
    ValidateUtil.validateLocalDependency(this.moduleModel, this.targetService.getBuildOption(), allDependency);

    return this.copyIntermediates();
  }
}
